<template>
<div>
  <MainHeader></MainHeader>
  <div class="row" style="margin-top: 80px ">
    <div class="col-lg-12">
      <div class="section-top text-center">
        <h2>My second-hand goods</h2>
        <p>管理，编辑，上架，下架</p>
      </div>
    </div>
  </div>
<!--  <section class="newsletter-area job-single section-padding">-->
<!--    <div class="container">-->
<!--      <div class="row">-->
<!--        <div class="col-lg-12">-->
<!--          <div class="section-top text-center">-->
<!--            <h2>Get job information daily</h2>-->
<!--            <p>Subscribe to our newsletter and get a coupon code!</p>-->
<!--          </div>-->
<!--        </div>-->
<!--      </div>-->
<!--      <div class="row">-->
<!--        <div class="col-lg-12">-->
<!--          <form action="#">-->
<!--            <input type="email" placeholder="Your email here" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your email here'" required>-->
<!--            <button type="submit" class="template-btn">subscribe now</button>-->
<!--          </form>-->
<!--        </div>-->
<!--      </div>-->
<!--    </div>-->
<!--  </section>-->
  <el-tabs type="border-card" class="container" style="margin: 10px auto;min-height: 800px;border-radius: 10px">
    <el-tab-pane >
      <span slot="label" style="font-size: 16px;"><i class="iconfont icon-shangpin" ></i>&nbsp;&nbsp;我发布的藏品</span>
      <div  style="display: flex;justify-content: flex-end;width: 100%;margin-top: 10px">
        <el-form :inline="true" >
        <el-form-item label="查询操作">
        <el-select v-model="operateValue" clearable placeholder="请选择"  @change="handleChangeFlag">
        <el-option  label="全部商品（包括已下架）" value="100"></el-option>
        <el-option  label="在线商品" value="1"></el-option>
        <el-option  label="已下架" value="2"></el-option>
        <el-option  label="已售出商品" value="4"></el-option>
      </el-select>
        </el-form-item>
        </el-form>
      </div>
      <div class="row">
        <div class="col-lg-12">
          <div class="main-content" v-for="item in myProduct " :key="item.id">
            <div class="single-content1">
              <div class="single-job mb-4 d-lg-flex justify-content-between">
                <div class="job-text">
                  <h4  style="width: 500px;display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 3;overflow: hidden;">名称：{{item.commname}}</h4>
                  <ul class="mt-4">
                    <li class="mb-3" style="width: 500px;display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 3;overflow: hidden;"><h5><i class="iconfont icon-miaoshu"></i> 描述:{{item.commdesc}}</h5></li>
                    <li class="mb-3"><h5><i class="iconfont icon-fenlei"></i> 种类:{{item.category}}</h5></li>
                    <li class="mb-3"><h5><i class="iconfont icon-jiage"></i> 价格{{item.thinkmoney}}</h5></li>
                    <li class="mb-3"><h5><i class="iconfont icon-shijian"></i> 上架时间:{{item.updatetime}}</h5></li>
                    <li class="mb-3"><h5><i class=" iconfont icon-beizhu"></i> 备注：</h5></li>
                  </ul>
                </div>
                <div class="job-img align-self-center">
                  <img :src="item.image" alt="商品图片" style="width: 200px">
                </div>
                <div style="display: flex;flex-direction: column;justify-content: space-around">
                  <button type="button" class="btn btn-primary" @click="updateItem(item)">更新信息</button>
                  <button type="button" class="btn btn-danger" @click="deleteItem(item.commid)">下架藏品</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-tab-pane>
    <el-tab-pane>
    <span slot="label" style="font-size: 16px"><i class="iconfont icon-fabu"></i>&nbsp;&nbsp;上架二手藏品</span>

      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="商品名称：" prop="commname">
          <el-input v-model="ruleForm.commname"></el-input>
        </el-form-item>
        <el-form-item label="类别："  prop="category">
          <el-input v-model="ruleForm.category"></el-input>
        </el-form-item>

        <el-form-item label="简介：" prop="commdesc">
          <el-input type="textarea" v-model="ruleForm.commdesc"></el-input>
        </el-form-item>
        <el-form-item label="常用选项：" >
          <el-select v-model="ruleForm.common" placeholder="请选择">
          <el-option label="自提" value="自提"></el-option>
            <el-option label="一口价，不讲价" value="一口价，不讲价"></el-option>
            <el-option label="选购前联系我" value="选购前联系我"></el-option>
          <el-option label="真心出售，可折扣" value="真心出售，可折扣"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品主图：">
          <el-upload
            :action="ossUrl"
            :before-remove="beforeRemove"
            :on-success="handleAvatarSuccess"
            multiple
            :limit="1"
            :on-exceed="handleExceed"
            >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传一个主图，且图片不能过大</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品辅图：" >
          <el-upload
            :action="ossUrl"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-success="handlePicsSuccess"
           >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="商品视频：" >
          <el-upload
            class="upload-demo"
            drag
            :on-success="handleVideoSuccess"
            :action="ossUrl"
            multiple>
            <i class="el-icon-upload"></i>

            <div class="el-upload__tip" slot="tip">只能上传一个视频，且视频不能过大</div><div class="el-upload__text">将视频文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>
        <el-form-item>
        <span style="color: #099e80">原价 </span> <el-input-number v-model="ruleForm.orimoney" @change="handleChange"  label="描述文字"></el-input-number>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <span style="color: red">现价 </span> <el-input-number v-model="ruleForm.thinkmoney" @change="handleChange"  label="描述文字"></el-input-number>
        </el-form-item>
        <el-form-item label="所在学校：">
          <el-input v-model="ruleForm.school"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-tab-pane>
  </el-tabs>
  <el-dialog title="修改信息" :visible.sync="dialogFormVisible">
    <el-form :model="updateInfo" :rules="rules" ref="ruleForm" label-width="100px">
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="updateInfo.commname"></el-input>
      </el-form-item>
        <el-form-item label="商品种类" >
          <el-input v-model="updateInfo.category"></el-input>
        </el-form-item>
      <el-form-item label="商品描述" >
        <el-input type="textarea"   :autosize="{ minRows: 3, maxRows: 5}" v-model="updateInfo.commdesc"></el-input>
      </el-form-item>
        <el-form-item label="商品价格" >
          <el-input v-model="updateInfo.thinkmoney"></el-input>
        </el-form-item>
      <el-form-item label="更新图片">
       <img :src="updateInfo.image" alt="商品图片" style="width: 200px"/>
        <el-upload
          :action="ossUrl"
          :on-success="handleSuccess"
          multiple
          :limit="1"
          :on-exceed="handleExceed"
          >
        <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleUpload">确 定</el-button>
    </div>
  </el-dialog>
  <MainFooter></MainFooter>
</div>
</template>

<script>
import MainHeader from '../pages/Home/header'
import MainFooter from '../pages/Home/footer'
import  {uuid} from '../utils/uuid'
import {baseUrl, ossUrl} from '../utils/Address'
export default {
  name: 'my',
  components: {MainFooter, MainHeader},
  mounted () {
    this.getUserGoods(1)
    this.getAuth()
  },
  data(){
    return {
      ossUrl:ossUrl,
      dialogFormVisible:false,
      updateInfo:{},
      activeName: '1',
      operateValue:'1',
      dialogImageUrl: '',
      dialogVisible: false,
      myProduct:{},
      ruleForm:{
      category: '',
      commdesc: '',
      commid: '',
      commname: '',
      common: '',
       image: '',
        orimoney: 59,
        thinkmoney: 39,
      otherimg: [],
      school: '',
      videourl: '',
      },
      auth:{

      },
      rules:{
        commname:[
           { required: true, message: '请填写商品名称', trigger: 'blur' },
        ],
        category:[
           { required: true, message: '请填写商品分类', trigger: 'blur' },
        ],
        commdesc:[
           { required: true, message: '请输入商品描述', trigger: 'blur' },
        ]
    }
    }
  },

  methods: {
    updateItem (item) {
      this.dialogFormVisible = true
      this.updateInfo = item
    },
    handleSuccess (res, file) {
      console.log(file)
      this.getAuth()
      var ossData = new FormData()
      ossData.append('name', file.name)
      let filename = file.name
      let picName = this.random_string(10) + this.get_suffix(filename)
      let keyValue = this.auth.dir + picName
      ossData.append('key', keyValue)
      ossData.append('policy', this.auth.policy)
      ossData.append('OSSAccessKeyId', this.auth.accessid)
      ossData.append('success_action_status', 200)
      ossData.append('signature', this.auth.signature)
      ossData.append('file', file.raw, file.name)
      this.axios.post('http://second-shop.oss-cn-shanghai.aliyuncs.com', ossData, {
        withCredentials: false,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        console.log(res)
        if (res.status === 200) {
          let Picsurl = 'http://' + this.auth.host + '/' + keyValue
          console.log(Picsurl)
          this.updateInfo.image = Picsurl
        }
      })
  },
    handleUpload(){
      this.dialogFormVisible=false
       this.axios.post(`${baseUrl}/changegoods/rel`,this.updateInfo).then(res=>{
         console.log(res)
         this.getUserGoods();
       })
    },
    handleChangeFlag (flag){
      this.getUserGoods(parseInt(flag))
    },
    async getAuth () {
      let res = await this.axios.post(`${baseUrl}/oss/policy`)
      this.auth = res.data
      console.log(this.auth)
    },
    getUserGoods (flag) {
      this.axios.get(`${baseUrl}/user/commodity/` + flag,).then(
        res => {
          this.myProduct = res.data.data
          console.log(this.myProduct)
        }
      ).catch(err => {
        console.log(err)
      })
    },
    get_suffix (filename) {
      let pos = filename.lastIndexOf('.')
      let suffix = ''
      if (pos != -1) {
        suffix = filename.substring(pos)
      }
      return suffix
    },
    random_string (len) {
      len = len || 32
      var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
      var maxPos = chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handlePicsSuccess (res, file) {
      console.log(file)
      this.getAuth()
      var ossData = new FormData()
      ossData.append('name', file.name)
      let filename = file.name
      let picName = this.random_string(10) + this.get_suffix(filename)
      let keyValue = this.auth.dir + picName
      ossData.append('key', keyValue)
      ossData.append('policy', this.auth.policy)
      ossData.append('OSSAccessKeyId', this.auth.accessid)
      ossData.append('success_action_status', 200)
      ossData.append('signature', this.auth.signature)
      ossData.append('file', file.raw, file.name)

      this.axios
        .post('http://second-shop.oss-cn-shanghai.aliyuncs.com', ossData, {
          withCredentials: false,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(res => {
        console.log(res)
        if (res.status === 200) {
          let Picsurl = 'http://' + this.auth.host + '/' + keyValue
          console.log(Picsurl)
          this.ruleForm.otherimg.push(Picsurl)
        }
      })
        .catch(error => {
          console.log(error)
        })
    },
    handleRemove (file) {
      console.log(file);
    },
    handleAvatarSuccess (res, file) {
      console.log(file)
      var ossData = new FormData()
      ossData.append('name', file.name)
      let filename = file.name
      let picName = this.random_string(10) + this.get_suffix(filename)
      let keyValue = this.auth.dir + picName
      ossData.append('key', keyValue)
      ossData.append('policy', this.auth.policy)
      ossData.append('OSSAccessKeyId', this.auth.accessid)
      ossData.append('success_action_status', 200)
      ossData.append('signature', this.auth.signature)
      ossData.append('file', file.raw, file.name)
      this.axios
        .post('http://second-shop.oss-cn-shanghai.aliyuncs.com', ossData, {
          withCredentials: false,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(res => {
        if (res.status === 200) {
          let url = 'http://' + this.auth.host + '/' + keyValue
          console.log(url)
          this.ruleForm.image = url
        }
      })
        .catch(error => {
          console.log(error)
        })
    },
    handleVideoSuccess (res, file) {
      console.log(file)
      this.getAuth()
      var ossData = new FormData()
      ossData.append('name', file.name)
      let filename = file.name
      let picName = this.random_string(10) + this.get_suffix(filename)
      let keyValue = this.auth.dir + picName
      ossData.append('key', keyValue)
      ossData.append('policy', this.auth.policy)
      ossData.append('OSSAccessKeyId', this.auth.accessid)
      ossData.append('success_action_status', 200)
      ossData.append('signature', this.auth.signature)
      ossData.append('file', file.raw, file.name)
      this.axios
        .post('http://second-shop.oss-cn-shanghai.aliyuncs.com', ossData, {
          withCredentials: false,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(res => {
        console.log(res)
        if (res.status === 200) {
          let Videosurl = 'http://' + this.auth.host + '/' + keyValue
          console.log(Videosurl)
          this.ruleForm.videourl = Videosurl
        }
      })
        .catch(error => {
          console.log(error)
        })
    },
    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    submitForm () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.ruleForm.commid = uuid(8, 16)
          console.log(this.ruleForm)
          this.axios.post(`${baseUrl}/relgoods/rel`, this.ruleForm).then(
            res => {
              if(res.data.data.status==='200'){
                this.$message.success('发布成功啦，快去看看吧')
                this.$refs.ruleForm.resetFields()
                this.ruleForm.common=''
              }
            }
          ).catch(err => {
            console.log(err)
          })
        } else {
          this.$message('请填写必选项！！！')
          return false;
        }
      });
    },
    resetForm () {
      this.$refs.ruleForm.resetFields()
      this.ruleForm.common=''
    },
    deleteItem (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios(`${baseUrl}/user/changecommstatus/${id}/4`).then(
          res => {
            console.log(res)

            if (res.data.status === 200) {
               this.$message.success('success')
              this.getUserGoods(1)
            } else {
              this.$message.error('删除失败啦，稍后尝试')
            }
          }
        ).catch(err => {
          console.log(err)
          this.$message.error('删除失败啦，服务器错误')
        })
      }).catch(() => {
        this.$message.info('您取消了删除')
      });
    },
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-3);
    }
  }
}
</script>

<style scoped>
.demo-ruleForm{
  width: 700px;
  margin: 20px auto;
}
.el-tabs__nav-scroll{
  height: 50px !important;
}
</style>
